import { watch } from "vue";
import { useUserFormInject } from "./useUserFormInject";
import { LogicLevel, LogicOperation } from "../../BizProjectForm/FormLogic";

interface OptionVisibilityChange {
  optionId: string;
  isVisible: boolean;
  previousVisibility: boolean;
}

export function useFormOptionLogic() {
  const { currentPageConfig, fieldOptionVisibilityMap, fieldOptionCheckStatusMap } = useUserFormInject();

  // 初始化选项的默认状态
  const initOptionVisibility = () => {
    // 处理选项的可见类型
    const newOptionVisibilityMap = new Map<string, OptionVisibilityChange>();
    const newFieldOptionCheckStatusMap = new Map<string, Set<string>>();

    Object.entries(currentPageConfig.value?.logicRuleMap || {}).forEach(([optionId, rule]) => {
      if (rule.level === LogicLevel.OPTION && rule.operation && rule.operation === LogicOperation.SHOW) {
        newOptionVisibilityMap.set(optionId, {
          optionId,
          previousVisibility: false,
          isVisible: false
        });
      } else if (rule.level === LogicLevel.OPTION && rule.operation && rule.operation === LogicOperation.CHECK) {
        const [questionId] = optionId.split("_");
        newFieldOptionCheckStatusMap.set(questionId, new Set());
      }
    });
    fieldOptionVisibilityMap.value = newOptionVisibilityMap;
    fieldOptionCheckStatusMap.value = newFieldOptionCheckStatusMap;
  };

  // 判断选项是否显示
  const isShowOption = (optionId: string) => {
    return !fieldOptionVisibilityMap.value.get(optionId) || fieldOptionVisibilityMap.value.get(optionId)?.isVisible;
  };

  /**
   * 监听题目是否选中状态 如果选中状态发生变化 则调用callback回调
   * @param key 题目id
   * @param callback 回调函数 会把被选中的 ID 回调
   */
  const initWatchCheckRule = (key: string, callback: Function) => {
    if (fieldOptionCheckStatusMap.value.get(key)) {
      watch(
        () => fieldOptionCheckStatusMap.value.get(key) as Set<string>,
        (val: Set<string>) => {
          console.log("logic check", val);
          if (val.size) {
            // 现在的选项都是数字 所以转成数字
            const optionIds = Array.from(val).map((id: string) => parseInt(id));
            callback(optionIds);
          }
        },
        {
          deep: true
        }
      );
    }
  };

  return {
    initOptionVisibility,
    isShowOption,
    initWatchCheckRule
  };
}

export type ReturnTypeOfUseFormOptionLogic = ReturnType<typeof useFormOptionLogic>;
